package com.iscreen.utils.db.connection;

import java.sql.DriverManager;
import java.sql.SQLException;

import com.iscreen.utils.db.connection.mysql.MySQLConnectionFactory;
import com.iscreen.utils.db.connection.settings.DBConnectionSettings;
import com.iscreen.utils.exceptions.IScreenException;
import com.iscreen.utils.exceptions.IScreenExceptionCodes;

public abstract class DBConnectionFactory
{

	protected DBConnectionSettings settings;

	protected abstract String getDriverClassName();

	protected abstract String getConnectionUrl();
	
	protected abstract DBErrorHandler getErrorHandler();

	private final static String JDBC_PREFIX = "jdbc:";

	public DBConnection getConnection() throws IScreenException
	{
		try
		{
			java.sql.Connection connection = DriverManager.getConnection(
					JDBC_PREFIX + getConnectionUrl(), settings.getUsername(),
					settings.getPassword());
			return new DBConnection(connection,getErrorHandler());
		}
		catch (SQLException e)
		{
			throw new IScreenException(IScreenExceptionCodes.DB_CONNECTION_ERROR, e);
		}
	}

	private void registerDriver() throws IScreenException
	{
		try
		{
			Class.forName(getDriverClassName());
		}
		catch (ClassNotFoundException e)
		{
			throw new IScreenException(IScreenExceptionCodes.DB_DRIVER_NOT_FOUND, e);
		}
	}

	protected void init(DBConnectionSettings dbConnectionSettings)
			throws IScreenException
	{
		settings = dbConnectionSettings;
		registerDriver();
	}

	public static DBConnectionFactory createFactory(String dbPropertiesFile)
			throws IScreenException
	{
		DBConnectionSettings dbConnectionSettings = new DBConnectionSettings(
				dbPropertiesFile);
		DBConnectionFactory factory;
		if (dbConnectionSettings.getDriver().equals(
				MySQLConnectionFactory.DRIVER_NAME))
		{
			factory = new MySQLConnectionFactory();
		}
		else
		{
			throw new IScreenException(IScreenExceptionCodes.DB_DRIVER_NOT_SUPPORTED, dbConnectionSettings
					.getDriver()
					+ " is not supported.");
		}

		factory.init(dbConnectionSettings);
		return factory;
	}

}
